import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  message,
  Row,
  Col,
  Table,
  Tag,
  Space,
  Typography,
  Alert,
  Statistic,
  Progress,
  Modal,
  Tabs,
  Switch,
  Divider,
  Timeline,
  Badge,
  Tooltip
} from 'antd';
import {
  SyncOutlined,
  SettingOutlined,
  ToolOutlined,
  HistoryOutlined,
  EditOutlined,
  SaveOutlined,
  PlayCircleOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;

const StrategyRebalance = () => {
  const [rebalanceStrategies, setRebalanceStrategies] = useState([
    {
      id: 1,
      name: '价值成长混合策略',
      type: '混合策略',
      autoRebalance: true,
      trigger: 'threshold',
      threshold: 5,
      frequency: 'monthly',
      lastRebalance: '2024-01-15',
      nextRebalance: '2024-02-15',
      deviation: 2.8,
      status: 'balanced'
    },
    {
      id: 2,
      name: '量化择时策略',
      type: '择时策略',
      autoRebalance: false,
      trigger: null,
      threshold: null,
      frequency: null,
      lastRebalance: '2024-01-10',
      nextRebalance: 'N/A',
      deviation: 8.5,
      status: 'deviation'
    },
    {
      id: 3,
      name: '低风险稳健策略',
      type: '稳健策略',
      autoRebalance: true,
      trigger: 'time',
      threshold: null,
      frequency: 'quarterly',
      lastRebalance: '2024-01-05',
      nextRebalance: '2024-04-05',
      deviation: 1.2,
      status: 'balanced'
    }
  ]);

  const [isSettingModalVisible, setIsSettingModalVisible] = useState(false);
  const [isManualModalVisible, setIsManualModalVisible] = useState(false);
  const [selectedStrategy, setSelectedStrategy] = useState(null);
  const [form] = Form.useForm();
  
  const handleOpenSettings = (record) => {
    setSelectedStrategy(record);
    form.setFieldsValue(record);
    setIsSettingModalVisible(true);
  };

  const handleSaveSettings = async () => {
    try {
      const values = await form.validateFields();
      setRebalanceStrategies(rebalanceStrategies.map(s => 
        s.id === selectedStrategy.id ? { ...s, ...values } : s
      ));
      message.success('再平衡设置已保存！');
      setIsSettingModalVisible(false);
    } catch (error) {
      console.error('设置保存失败:', error);
    }
  };

  const handleOpenManualRebalance = (record) => {
    setSelectedStrategy(record);
    setIsManualModalVisible(true);
  };

  const handleExecuteRebalance = () => {
    message.info('正在执行调仓...');
    setTimeout(() => {
      message.success('调仓指令已发送！');
      setIsManualModalVisible(false);
    }, 2000);
  };

  const columns = [
    {
      title: '策略名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '自动再平衡',
      dataIndex: 'autoRebalance',
      key: 'autoRebalance',
      width: 120,
      render: (auto, record) => (
        <Switch 
          checked={auto} 
          onChange={(checked) => 
            setRebalanceStrategies(rebalanceStrategies.map(s => 
              s.id === record.id ? { ...s, autoRebalance: checked } : s
            ))
          }
        />
      ),
    },
    {
      title: '触发方式',
      dataIndex: 'trigger',
      key: 'trigger',
      width: 120,
      render: (trigger) => {
        if (!trigger) return 'N/A';
        const texts = { threshold: '偏离度阈值', time: '固定时间' };
        return <Tag color="blue">{texts[trigger]}</Tag>;
      },
    },
    {
      title: '最大偏离度',
      dataIndex: 'deviation',
      key: 'deviation',
      width: 120,
      render: (deviation, record) => (
        <Progress 
          percent={deviation} 
          steps={10} 
          strokeColor={deviation > record.threshold ? '#ff4d4f' : '#52c41a'}
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) => (
        <Badge 
          status={status === 'balanced' ? 'success' : 'warning'} 
          text={status === 'balanced' ? '已平衡' : '需调仓'} 
        />
      ),
    },
    {
      title: '上次调仓',
      dataIndex: 'lastRebalance',
      key: 'lastRebalance',
      width: 150,
    },
    {
      title: '下次计划',
      dataIndex: 'nextRebalance',
      key: 'nextRebalance',
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (_, record) => (
        <Space>
          <Button 
            type="primary" 
            ghost 
            icon={<ToolOutlined />}
            onClick={() => handleOpenManualRebalance(record)}
            disabled={record.status === 'balanced'}
          >
            主动调仓
          </Button>
          <Button 
            icon={<SettingOutlined />}
            onClick={() => handleOpenSettings(record)}
          >
            设置
          </Button>
          <Button icon={<HistoryOutlined />}>历史</Button>
        </Space>
      ),
    },
  ];
  
  const mockHoldings = [
    { fund: '华夏成长混合', current: 25.5, target: 25, diff: 0.5 },
    { fund: '易方达消费行业', current: 20.3, target: 25, diff: -4.7 },
    { fund: '嘉实增长混合', current: 18.7, target: 20, diff: -1.3 },
    { fund: '南方稳健成长', current: 15.2, target: 15, diff: 0.2 },
    { fund: '博时主题行业', current: 20.3, target: 15, diff: 5.3 },
  ];
  
  const rebalancePlanColumns = [
    { title: '基金名称', dataIndex: 'fund', key: 'fund' },
    { title: '当前权重(%)', dataIndex: 'current', key: 'current' },
    { title: '目标权重(%)', dataIndex: 'target', key: 'target' },
    { title: '权重差异(%)', dataIndex: 'diff', key: 'diff', render: (d) => <span style={{ color: d > 0 ? '#ff4d4f' : '#52c41a' }}>{d.toFixed(1)}</span>},
    { title: '建议操作', key: 'action', render: (_, record) => <Tag color={record.diff > 0 ? 'red' : 'green'}>{record.diff > 0 ? '卖出' : '买入'}</Tag>}
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>策略再平衡</Title>
      <Paragraph type="secondary">配置策略的再平衡规则，支持自动和手动调仓</Paragraph>

      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <SyncOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
            <span>再平衡仪表盘</span>
          </div>
        }
      >
        <Table
          dataSource={rebalanceStrategies}
          columns={columns}
          rowKey="id"
          pagination={false}
        />
      </Card>
      
      {/* 再平衡设置模态框 */}
      <Modal
        title="再平衡设置"
        open={isSettingModalVisible}
        onOk={handleSaveSettings}
        onCancel={() => setIsSettingModalVisible(false)}
        width={600}
        okText="保存设置"
      >
        {selectedStrategy && (
          <Form
            form={form}
            layout="vertical"
            initialValues={{ ...selectedStrategy }}
          >
            <Form.Item name="autoRebalance" label="开启自动再平衡" valuePropName="checked">
              <Switch />
            </Form.Item>
            
            <Form.Item
              noStyle
              shouldUpdate={(prev, current) => prev.autoRebalance !== current.autoRebalance}
            >
              {({ getFieldValue }) => getFieldValue('autoRebalance') && (
                <>
                  <Form.Item name="trigger" label="触发方式" rules={[{ required: true }]}>
                    <Select placeholder="请选择触发方式">
                      <Option value="threshold">偏离度阈值</Option>
                      <Option value="time">固定时间</Option>
                    </Select>
                  </Form.Item>
                  
                  <Form.Item
                    noStyle
                    shouldUpdate={(prev, current) => prev.trigger !== current.trigger}
                  >
                    {({ getFieldValue }) => getFieldValue('trigger') === 'threshold' && (
                      <Form.Item name="threshold" label="偏离度阈值(%)" rules={[{ required: true }]}>
                        <InputNumber min={1} max={50} style={{ width: '100%' }} />
                      </Form.Item>
                    )}
                  </Form.Item>

                  <Form.Item
                    noStyle
                    shouldUpdate={(prev, current) => prev.trigger !== current.trigger}
                  >
                    {({ getFieldValue }) => getFieldValue('trigger') === 'time' && (
                      <Form.Item name="frequency" label="再平衡频率" rules={[{ required: true }]}>
                        <Select placeholder="请选择再平衡频率">
                          <Option value="monthly">每月</Option>
                          <Option value="quarterly">每季度</Option>
                          <Option value="yearly">每年</Option>
                        </Select>
                      </Form.Item>
                    )}
                  </Form.Item>
                </>
              )}
            </Form.Item>
          </Form>
        )}
      </Modal>

      {/* 主动调仓模态框 */}
      <Modal
        title="主动调仓"
        open={isManualModalVisible}
        onOk={handleExecuteRebalance}
        onCancel={() => setIsManualModalVisible(false)}
        width={800}
        okText="执行调仓"
      >
        {selectedStrategy && (
          <div>
            <Alert
              message={`您正在为 "${selectedStrategy.name}" 进行主动调仓`}
              description="系统已根据目标权重生成调仓计划，请审核后执行。"
              type="info"
              showIcon
              style={{ marginBottom: 24 }}
            />
            <Table
              dataSource={mockHoldings}
              columns={rebalancePlanColumns}
              rowKey="fund"
              pagination={false}
              size="small"
            />
            <Divider />
            <Statistic
              title="预计交易笔数"
              value={mockHoldings.length}
              style={{ textAlign: 'right' }}
            />
          </div>
        )}
      </Modal>
    </div>
  );
};

export default StrategyRebalance; 